package com.gitee.zycra.future.job.dao;

import com.gitee.zycra.future.job.common.exceptions.IdGeneratorException;
import com.gitee.zycra.future.job.common.model.MachineId;
import com.gitee.zycra.future.job.common.util.IPUtil;
import com.gitee.zycra.jdbc.common.BaseDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;

import java.net.InetAddress;

/**
 * @author zycra
 */
@Repository
public class MachineIdDao extends BaseDao<MachineId> {

    @Value("${spring.application.name}")
    private String applicationName;

    @Bean
    public MachineId machineId() {
        InetAddress localHostAddress = IPUtil.getLocalHostAddress();
        if (localHostAddress == null) {
            throw new IdGeneratorException("get local ip failed");
        }
        MachineId machineId = new MachineId().setApplicationName(applicationName).setNodeIp(localHostAddress.getHostAddress());
        try {
            MachineId dbModel = selectOneTableByNotNullColumnEquals(machineId);
            if (dbModel != null) {
                return dbModel;
            }
            insertIntoTable(machineId);
            dbModel = selectOneTableByNotNullColumnEquals(machineId);
            if (dbModel != null) {
                return dbModel;
            }
        } catch (Exception e) {
            return null;
        }
        throw new IdGeneratorException("insert machine id failed");
    }
}
